package com.example.dangerouscargodriver.ui.activity;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.baiju.bean.CityBean;
import com.baiju.netmanager.Http.IHttpRequest;
import com.baiju.style.citylist.Toast.ToastUtils;
import com.example.dangerouscargodriver.adapter.LineInfoAdapter;
import com.example.dangerouscargodriver.controller.AuthController;
import com.example.dangerouscargodriver.entry.LineInfo;
import com.example.dangerouscargodriver.entry.LineSearchInfo;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.ui.listener.OnLoadMoreListener;
import com.example.dangerouscargodriver.utils.AppManager;
import com.example.dangerouscargodriver.widget.ActionBar;
import com.example.dangerouscargodriver.R;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class PersonalLineListActivity extends HttpRequestActivity implements View.OnClickListener {

	private static final String TAG = "LineListActivity";

	private ActionBar mActionBar = null;
	private Button mAddLine = null;
	private List<LineInfo> mLineInfo = null;
	private RecyclerView mLineRV = null;
	private LineInfoAdapter mAdapter = null;
	private int mOperateId = -1;
	private boolean mCreate = true;
	private int mTotalLineInfoNum = 0;
	private SwipeRefreshLayout mLineLayout = null;
	private OnLoadMoreListener mOnLoadListener = null;

	private TextView mLineNum = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.initHttpComponent(PersonalLineListActivity.class);
		setContentView(R.layout.activity_personal_line_list);
		AppManager.getAppManager().addActivity(this);

		mLineInfo = new ArrayList<>();
		mAdapter = new LineInfoAdapter();
		mAdapter.setUserActionListener(new LineInfoAdapter.IUserActionListener() {
			@Override
			public void onEdit(int position) {
				executeEditLineInfo(position);
			}

			@Override
			public void onDelete(int position) {
				executeDeleteLineInfo(position);
			}
		});
		mLineLayout = findViewById(R.id.rv_personal_line_layout);
		//设置下拉时圆圈的颜色（可以尤多种颜色拼成）
		mLineLayout.setColorSchemeResources(R.color.base_yellow);
		//设置下拉时圆圈的背景颜色（这里设置成白色）
		mLineLayout.setProgressBackgroundColorSchemeResource(android.R.color.white);

		mLineLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
			@Override
			public void onRefresh() {
				Log.d(TAG, "onRefresh");
				executeSearchLineListAction(true);
			}
		});

		mAddLine = findViewById(R.id.btn_personal_add_line);
		mAddLine.setOnClickListener(this);

		mLineRV = findViewById(R.id.rv_personal_line_list);
		LinearLayoutManager layoutManager = new LinearLayoutManager(getBaseContext());
		mLineRV.setLayoutManager(layoutManager);
		mLineRV.setAdapter(mAdapter);
		mOnLoadListener = new OnLoadMoreListener() {
			@Override
			protected void onLoading(int countItem, int lastItem) {
				Log.d(TAG, "onLoading");
				executeSearchLineListAction(false);
			}
		};
		mLineRV.addOnScrollListener(mOnLoadListener);
		mLineNum = findViewById(R.id.tv_line_num);

		mActionBar = findViewById(R.id.actionBarPersonalLineList);
		mActionBar.setOnBackClickListener( new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		executeSearchLineListAction(true);
	}

	private void executeEditLineInfo(int index){
		if(mOperateId != -1){
			return;
		}
		mOperateId = index;
		Intent intent = new Intent(this, PersonalModifyLineInfoActivity.class);
		CityBean startCityBean = new CityBean();
		startCityBean.setName(mLineInfo.get(mOperateId).getFrom_addr());
		startCityBean.setId(mLineInfo.get(mOperateId).getFrom_id());
		intent.putExtra("start", startCityBean);

		CityBean endCityBean = new CityBean();
		endCityBean.setName(mLineInfo.get(mOperateId).getTo_addr());
		endCityBean.setId(mLineInfo.get(mOperateId).getTo_id());
		intent.putExtra("end", endCityBean);

		intent.putExtra("srid", mLineInfo.get(mOperateId).getId());

		startActivity(intent);
		mOperateId = -1;
	}

	private void executeDeleteLineInfo(int index){
		if(mOperateId != -1){
			return;
		}
		mOperateId = index;
		HashMap<String, String> header = new HashMap<>();
		header.put("token", AuthController.Instance().getToken());

		sendHttpRequest(IHttpRequest.RequestMethod.DELETE_METHOD,
				RemoteAPI.REQUEST_V1_USER_SR + "/" + mLineInfo.get(index).getId(),
				header,
				null,
				RemoteAPICmd.REQUEST_V1_USER_SR_DELETE);
	}

	private void executeSearchLineListAction(boolean refresh){
		HashMap<String, String> header = new HashMap<>();
		header.put("token", AuthController.Instance().getToken());

		HashMap<String, String> param = new HashMap<>();

		if(refresh) {
			mTotalLineInfoNum = 0;
			mLineInfo.clear();
			param.put("page", "1");
			sendHttpRequest(IHttpRequest.RequestMethod.GET_METHOD,
					RemoteAPI.REQUEST_V2_USER_SR,
					header,
					param,
					RemoteAPICmd.REQUEST_V2_USER_SR);
		}
		else{
			if(mLineInfo.size() < mTotalLineInfoNum) {
				param.put("page", String.valueOf(mLineInfo.size() / 20 + 1));
				sendHttpRequest(IHttpRequest.RequestMethod.GET_METHOD,
						RemoteAPI.REQUEST_V2_USER_SR,
						header,
						param,
						RemoteAPICmd.REQUEST_V2_USER_SR_PAGE);
			}
			else{

			}
		}
	}


	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.btn_personal_add_line){
			Intent intent = new Intent(this, PersonalAddLineInfoActivity.class);
			startActivity(intent);
		}
		else{

		}
	}

	private void refreshLineListView() {
		mAdapter.clearData();
		Log.d(TAG, "mLineInfo.size: " + mLineInfo.size());
		Log.d(TAG, "mLineInfo: " + mLineInfo.toString());
		mAdapter.appendData(mLineInfo);
		mAdapter.notifyDataSetChanged();
	}

	@Override
	protected void onHttpResponse(int actionId, String response) {
		try {
			JSONObject res = new JSONObject(response);
			Gson gson = new Gson();
			if(actionId == RemoteAPICmd.REQUEST_V2_USER_SR) {
				Log.d(TAG, "onResponse: " + response);
				ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
				if(responseInfo != null && responseInfo.getStatus() == 1){
					LineSearchInfo searchInfo = gson.fromJson(res.getJSONObject("data").toString(),
							LineSearchInfo.class);
					if(searchInfo.getCount() > 0){
						mTotalLineInfoNum = searchInfo.getCount();
						mLineNum.setText(String.valueOf(mTotalLineInfoNum) + "/100");
						mLineInfo = searchInfo.getList();
						refreshLineListView();
					}
				}
				mLineLayout.setRefreshing(false);
			}
			else if(actionId == RemoteAPICmd.REQUEST_V2_USER_SR_PAGE) {
				Log.d(TAG, "onResponse: " + response);
				ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
				if(responseInfo != null && responseInfo.getStatus() == 1){
					LineSearchInfo searchInfo = gson.fromJson(res.getJSONObject("data").toString(),
							LineSearchInfo.class);
					Log.d(TAG, "mLineInfo.size: " + mLineInfo.size());
					if(searchInfo.getCount() > 0){
						List<LineInfo> lineInfos = searchInfo.getList();
						for(int index = 0; index < lineInfos.size(); index++){
							mLineInfo.add(lineInfos.get(index));
						}

						refreshLineListView();
					}
				}
			}
			else if(actionId == RemoteAPICmd.REQUEST_V1_USER_SR_DELETE){
				Log.d(TAG, "onResponse: " + response);
				ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
				if(responseInfo != null && responseInfo.getStatus() == 1){
					if(mOperateId != -1) {
						mAdapter.removeData(mOperateId);
						mLineInfo.remove(mOperateId);
					}
					else{
						/**/
					}
				}
				else{

				}
				mOperateId = -1;
			}
			else{
				/**/
			}
		}
		catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onHttpErrorResponse(int actionId, String response) {
		if(actionId == RemoteAPICmd.REQUEST_V2_USER_SR) {
			mLineLayout.setRefreshing(false);
		}
		else if(actionId == RemoteAPICmd.REQUEST_V1_USER_SR_DELETE){
			mOperateId = -1;
		}
		else{

		}
	}

	@Override
	public void onResume(){
		super.onResume();
		if(!mCreate) {
			executeSearchLineListAction(true);
		}
		else{
			mCreate = false;
		}
	}

	@Override
	public void onDestroy(){
		super.onDestroy();
		Log.d(TAG, "onDestroy");
	}
}